package com.dxysun.sql.dbutils;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import com.dxysun.sql.domain.User;

public class TestCRUD
{

	public static void main(String[] args) throws Exception
	{
		//		new TestCRUD().addUser();
		new TestCRUD().queryUser();
		//		 new TestCRUD().queryUserUseBeanListHandle();
	}

	/**
	 * 添加用户的方法
	 */
	public void addUser() throws SQLException
	{
		DruidUtils.init();
		QueryRunner queryRunner = DruidUtils.getQueryRunner();
		String sql = "insert into dxy_test.t_user(user_name,real_name)values('aaa','bbbb')";
		int i = queryRunner.update(DruidUtils.getConnection(), sql);
		System.out.println(i);
	}

	/**
	 * 查询所有的用户信息
	 * @throws Exception
	 */
	public void queryUser() throws Exception
	{
		DruidUtils.init();
		QueryRunner queryRunner = DruidUtils.getQueryRunner();
		String sql = "select * from dxy_test.t_user";
		List<User> list = queryRunner.query(sql, rs -> {
			List<User> list1 = new ArrayList<>();
			while (rs.next())
			{
				User user = new User();
				user.setId(rs.getInt("id"));
				user.setUserName(rs.getString("user_name"));
				user.setRealName(rs.getString("real_name"));
				user.setPassword(rs.getString("password"));
				list1.add(user);
			}
			return list1;
		});
		for (User user : list)
		{
			System.out.println(user);
		}
	}

	/**
	 * 通过ResultHandle的实现类处理查询
	 */
	public void queryUserUseBeanListHandle() throws Exception
	{
		DruidUtils.init();
		QueryRunner queryRunner = DruidUtils.getQueryRunner();
		String sql = "select * from dxy_test.t_user";
		// 不会自动帮助我们实现驼峰命名的转换
		List<User> list = queryRunner.query(sql, new BeanListHandler<>(User.class));
		for (User user : list)
		{
			System.out.println(user);
		}
	}

}
